package exercises;

import java.io.*;
import java.util.*;
import java.util.stream.Collectors;

public class FileDealV2 {
    // 中文正则
    final static String REGEX_CHINESE = "[\u4e00-\u9fa5]";
    final static String REGEX = ",";
    String filePath;
    public FileDealV2(String filePath) {
        this.filePath = filePath;
    }

     Boolean inspectFile() {
        File file = new File(filePath);
        return file.exists() && !file.isDirectory() && file.length() != 0;
    }

    public Map dealFile() {
        Map<String, Long> map = new HashMap<>();
        try {
            //读取文件
            FileInputStream fis = new FileInputStream(filePath);
            BufferedReader br = new BufferedReader(new InputStreamReader(fis));
            String temp;
            while ((temp = br.readLine()) != null) {
                temp = temp.replaceAll(REGEX_CHINESE, "").replaceAll("\\d+", "");
                //初始化计数器
                long count;
                Map<String, Long> countMap = Arrays.stream(temp.split(REGEX)).collect(Collectors.groupingBy(p -> p, Collectors.counting()));
                for(String key : countMap.keySet()){
                    if (map.containsKey(key)) {
                        count = map.get(key);
                        map.put(key, count + countMap.get(key));
                    } else {
                        map.put(key, countMap.get(key));
                    }

                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return map;
    }
    public void outPut(Map map) throws IOException {
        System.out.println(map);
        List<Map.Entry<String, Long>> list = new ArrayList<>(map.entrySet());
        File file = new File("output/countMaps.txt");
        BufferedWriter bf = new BufferedWriter(new FileWriter(file));
        try {

            for (Map.Entry<String, Long> entry : list) {
                System.out.println(entry.getKey() + ":" + entry.getValue());
                bf.write(entry.getKey() + ":" + entry.getValue());
                bf.newLine();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        finally {
            try {
                bf.close();
            }
            catch (Exception e) {

            }
        }

    }
}


